<template>
	<view class="container">
		<view class="header">
			<view class="title">采购单详情</view>
		</view>

		<view class="content" v-if="formData._id">
			<!-- 基本信息 -->
			<view class="info-group">
				<uni-forms ref="form" :modelValue="formData" :label-width="100">
					<uni-forms-item label="采购单名称">
						<uni-easyinput type="text" v-model="formData.title" :disabled="true" />
					</uni-forms-item>
					<uni-forms-item label="采购单编号">
						<uni-easyinput type="text" v-model="formData.serial_number" :disabled="true" />
					</uni-forms-item>
					<uni-forms-item label="详细描述">
						<uni-easyinput type="textarea" v-model="formData.description" :disabled="true" />
					</uni-forms-item>
					<uni-forms-item label="起始价格">
						<uni-easyinput type="digit" v-model="formData.start_price" :disabled="true" />
					</uni-forms-item>
					<uni-forms-item label="报价截止时间" name="end_time">
						<uni-datetime-picker type="datetime" v-model="formData.end_time" :disabled="!isEditing" />
					</uni-forms-item>
					<uni-forms-item label="状态">
						<uni-data-select v-model="formData.status" :localdata='[{"value":"bidding","text":"竞价中"},{"value":"finished","text":"已结束"}]' :disabled="!isEditing"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="创建时间">
						<uni-easyinput :value="formatDate(formData.create_time)" :disabled="true" />
					</uni-forms-item>
				</uni-forms>
			</view>

			<!-- 附件 -->
			<view class="info-group" v-if="formData.attachments && formData.attachments.length > 0">
				<view class="info-item">
					<text class="label">采购附件:</text>
					<view class="attachments">
						<view class="attachment" v-for="(attachment, index) in formData.attachments" :key="index">
							<text class="attachment-name">{{ attachment.name }}</text>
							<button class="download-btn" @click="downloadAttachment(attachment.url)">下载</button>
						</view>
					</view>
				</view>
			</view>

			<!-- 报价列表 -->
			<view class="bids-section" v-if="bids.length > 0">
				<view class="sub-title">报价记录</view>
				<!-- 采购方视图 -->
				<view v-if="isOwner" class="bids-list">
					<view class="bid-item" v-for="(bid, index) in bids" :key="bid._id">
						<view class="bid-info">
							<text class="rank">第 {{ index + 1 }} 名</text>
							<text class="supplier">供应商: {{ bid.supplier_user_id[0] ? bid.supplier_user_id[0].nickname || bid.supplier_user_id[0].username : '未知' }}</text>
							<text class="amount">报价: ¥{{ bid.amount }}</text>
						</view>
						<button v-if="formData.status === 'finished' && !formData.winner_supplier_id" class="action-btn award-btn" @click="award(bid)">选定</button>
						<text v-if="formData.winner_supplier_id === bid.supplier_user_id[0]._id" class="winner-tag">已选定</text>
					</view>
				</view>
				<!-- 供应商视图 -->
				<view v-else class="bids-list">
					<view class="bid-item my-bid">
						<text class="rank">我的排名: 第 {{ myRank }} 名</text>
						<text class="amount">我的报价: ¥{{ myBid.amount }}</text>
					</view>
					<view class="tip">为保护隐私，其他供应商的报价信息已隐藏。</view>
				</view>
			</view>
			<view v-else class="no-data">
				<text>暂无报价记录</text>
			</view>

			<!-- 操作按钮 -->
			<view class="action-bar">
				<!-- 采购方操作 -->
				<template v-if="isOwner">
					<button v-if="!isEditing && formData.status === 'bidding'" class="action-btn" @click="isEditing = true">编辑</button>
					<button v-if="isEditing" class="action-btn save-btn" @click="saveAuction">保存</button>
					<button v-if="isEditing" class="action-btn" @click="isEditing = false">取消</button>
				</template>
				<!-- 供应商操作 -->
				<template v-else>
					<button class="action-btn bid-btn" @click="goToBidding" :disabled="formData.status !== 'bidding'">
						{{ myBid ? '修改报价' : '去报价' }}
					</button>
				</template>
				<button class="action-btn back-btn" @click="navigateBack">返回</button>
			</view>
		</view>

		<view class="loading" v-else>
			<text>加载中...</text>
		</view>
	</view>
</template>

<script>
	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'auctions';

	export default {
		data() {
			return {
				formData: {},
				currentUser: {},
				isOwner: false,
				isEditing: false,
				bids: [],
				myBid: null,
				myRank: 0
			}
		},
		onLoad(e) {
			const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {};
			this.currentUser = {
				_id: userInfo._id,
				role: userInfo.role || []
			};

			if (e.id) {
				this.formData._id = e.id
				this.getDetail()
			}
		},
		methods: {
			getDetail() {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(this.formData._id).get().then((res) => {
					const data = res.result.data[0]
					if (data) {
						this.formData = data
						this.isOwner = this.currentUser._id === data.user_id || this.currentUser.role.includes('admin');
						this.getBids();
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			getBids() {
				db.collection('bids,uni-id-users')
					.where({
						auction_id: this.formData._id
					})
					.field('amount,create_time,supplier_user_id{_id,nickname,username}')
					.orderBy('amount', 'asc')
					.orderBy('create_time', 'asc')
					.get()
					.then(res => {
						const bids = res.result.data;
						this.bids = bids;

						if (!this.isOwner) {
							const myBidIndex = bids.findIndex(bid => bid.supplier_user_id[0]._id === this.currentUser._id);
							if (myBidIndex !== -1) {
								this.myBid = bids[myBidIndex];
								this.myRank = myBidIndex + 1;
							}
						}
					}).catch(err => {
						console.error('获取报价列表失败', err);
					})
			},
			saveAuction() {
				this.$refs.form.validate().then(res => {
					db.collection(dbCollectionName).doc(this.formData._id).update({
						end_time: this.formData.end_time,
						status: this.formData.status
					}).then(() => {
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
						this.isEditing = false;
						this.getDetail();
					}).catch(err => {
						uni.showModal({
							content: err.message || '保存失败',
							showCancel: false
						});
					})
				})
			},
			award(bid) {
				uni.showModal({
					title: '确认',
					content: `确定要将此采购单授予该供应商吗？`,
					success: (res) => {
						if (res.confirm) {
							db.collection(dbCollectionName).doc(this.formData._id).update({
								winner_supplier_id: bid.supplier_user_id[0]._id,
								status: 'finished'
							}).then(() => {
								uni.showToast({
									title: '授标成功',
									icon: 'success'
								});
								this.getDetail();
							})
						}
					}
				});
			},
			formatDate(timestamp) {
				if (!timestamp) return ''
				const date = new Date(timestamp)
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
			},
			statusText(status) {
				const statusMap = {
					'bidding': '竞价中',
					'finished': '已结束'
				}
				return statusMap[status] || status
			},
			downloadAttachment(url) {
				uni.downloadFile({
					url: url,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.saveFile({
								tempFilePath: res.tempFilePath,
								success: function(saveRes) {
									uni.showToast({
										title: '文件已保存到本地',
										icon: 'success'
									})
								}
							})
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						})
					}
				})
			},
			goToBidding() {
				uni.navigateTo({
					url: `/pages/bids/add?auctionId=${this.formData._id}`
				})
			},
			navigateBack() {
				uni.navigateBack()
			}
		}
	}
</script>

<style scoped>
	.container {
		padding: 20rpx;
		background-color: #f9f9f9;
		min-height: 100vh;
	}
	.header {
		margin-bottom: 30rpx;
	}
	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	.content {
		background-color: white;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		padding: 30rpx;
	}
	.info-group {
		margin-bottom: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
		padding-bottom: 20rpx;
	}
	.info-group:last-child {
		border-bottom: none;
	}
	.info-item {
		margin-bottom: 20rpx;
	}
	.label {
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 10rpx;
	}
	.value {
		color: #666;
		font-size: 28rpx;
	}
	.value.price {
		color: #ff4d4f;
		font-size: 32rpx;
		font-weight: bold;
	}
	.value.bidding {
		color: #007AFF;
	}
	.value.finished {
		color: #999;
	}
	.attachments {
		margin-top: 10rpx;
	}
	.attachment {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		background-color: #f9f9f9;
		border-radius: 8rpx;
		margin-bottom: 10rpx;
	}
	.attachment-name {
		flex: 1;
		font-size: 26rpx;
		color: #333;
	}
	.download-btn {
		padding: 10rpx 20rpx;
		background-color: #007AFF;
		color: white;
		border-radius: 6rpx;
		font-size: 24rpx;
	}
	.action-bar {
		display: flex;
		justify-content: center;
		margin-top: 40rpx;
	}
	.action-btn {
		padding: 20rpx 40rpx;
		font-size: 28rpx;
		border-radius: 10rpx;
		margin: 0 20rpx;
	}
	.bid-btn {
		background-color: #007AFF;
		color: white;
	}
	.bid-btn[disabled] {
		background-color: #ccc;
	}
	.back-btn {
		background-color: #f0f0f0;
		color: #333;
	}
	.save-btn {
		background-color: #4cd964;
		color: white;
	}
	.award-btn {
		background-color: #ff9500;
		color: white;
		padding: 10rpx 20rpx;
		font-size: 24rpx;
	}
	.loading, .no-data {
		text-align: center;
		padding: 100rpx;
		color: #999;
	}
	.bids-section {
		margin-top: 40rpx;
	}
	.sub-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		border-bottom: 2rpx solid #eee;
		padding-bottom: 15rpx;
	}
	.bid-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		background-color: #f9f9f9;
		border-radius: 8rpx;
		margin-bottom: 15rpx;
	}
	.bid-item.my-bid {
		background-color: #e6fffb;
		border: 1rpx solid #007AFF;
	}
	.bid-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}
	.rank {
		font-weight: bold;
		font-size: 30rpx;
	}
	.supplier, .amount {
		font-size: 28rpx;
		color: #333;
		margin-top: 5rpx;
	}
	.winner-tag {
		color: #4cd964;
		font-weight: bold;
	}
	.tip {
		font-size: 24rpx;
		color: #999;
		text-align: center;
		margin-top: 20rpx;
	}
</style>
